package com.axx.android.profile;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.home.model.User;
import com.axx.android.letter.activity.RecipientActivity;
import com.axx.android.profile.kettle.KettleActivity;
import com.axx.android.profile.like.LikeActivity;
import com.axx.android.profile.message.activity.MessageActivity;
import com.axx.android.profile.tool.ToolActivity;
import com.axx.android.setting.SettingActivity;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.axx.android.utils.ImageLoader;
import com.axx.android.utils.ImageUtils;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class ProfileActivity extends BaseActivity {

    @Bind(R.id.iv_bg)
    ImageView ivBg;
    @Bind(R.id.iv_header)
    ImageView ivHeader;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.layout_header)
    RelativeLayout layoutHeader;
    @Bind(R.id.layout_profile_message)
    LinearLayout layoutProfileMessage;
    @Bind(R.id.layout_profile_hole)
    LinearLayout layoutProfileHole;
    @Bind(R.id.layout_send_friend)
    LinearLayout layoutSendFriend;
    @Bind(R.id.layout_profile_like)
    LinearLayout layoutProfileLike;
    @Bind(R.id.view_sex)
    View viewSex;
    @Bind(R.id.btn_kettle)
    Button btnKettle;
    @Bind(R.id.layout_tool)
    LinearLayout layoutTool;
    @Bind(R.id.layout_album)
    LinearLayout layoutAlbum;
    @Bind(R.id.layout_setting)
    LinearLayout layoutSetting;

    @Override
    public int getLayoutId() {
        return R.layout.activity_profile;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        tvName.setText(LetterApp.authUser.getNickName());
        ImageLoader.loadRoundImage(LetterApp.authUser.getHeadPic(), ivHeader, this);
        ImageLoader.loadImage(LetterApp.authUser.getBackPic(), ivBg, this);
        if (LetterApp.authUser.getSex().equals("M")) {
            viewSex.setBackgroundResource(R.drawable.ic_sex_man);
        }
    }

    @OnClick({R.id.iv_header, R.id.layout_album, R.id.layout_tool, R.id.btn_kettle, R.id.layout_profile_message, R.id.layout_profile_hole, R.id.layout_send_friend, R.id.layout_profile_like, R.id.layout_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_profile_message:
                startActivity(new Intent(this, MessageActivity.class));
                break;
            case R.id.layout_profile_hole:
                Intent intent1 = new Intent(this, RecipientActivity.class);
                String json = GsonUtils.toJson(LetterApp.authUser);
                try {
                    User.UserListBean model = GsonUtils.fromJson(json, new TypeToken<User.UserListBean>() {
                    });
                    intent1.putExtra("model", model);
                    intent1.putExtra("from", "profile");
                    startActivity(intent1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
            case R.id.layout_send_friend:
                startActivity(new Intent(this, SendFriendActivity.class));
                break;
            case R.id.layout_profile_like:
                startActivity(new Intent(this, LikeActivity.class));
                break;
            case R.id.layout_setting:
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.id.layout_album:
                Intent intent = new Intent(this, KettleActivity.class);
                intent.putExtra("target", LetterApp.authUser.getId());
                startActivity(intent);
                break;
            case R.id.layout_tool:
                startActivity(new Intent(this, ToolActivity.class));
                break;
            case R.id.iv_header:
                uploadHeader();
                break;
        }
    }

    private int imageType = 0;

    private void uploadHeader() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).setItems(new String[]{"上传头像", "上传背景图", "修改名称"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (i == 2) {
                    showModifyNameDialog();
                } else {
                    imageType = i;
                    MultiImageSelector.create().single().start(ProfileActivity.this, 200);
                }


            }
        }).create();
        alertDialog.show();
    }

    private void showModifyNameDialog() {
        View view = View.inflate(this, R.layout.view_dialog_modify_name, null);
        final EditText et_name = (EditText) view.findViewById(R.id.et_name);
        et_name.setText(LetterApp.authUser.getNickName());
        final AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("修改名称").setView(view).setNegativeButton("取消", null).setPositiveButton("确定", null).create();
        alertDialog.show();
        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(et_name.getText().toString())) {
                    showToast("请输入要修改的昵称");
                    return;
                }
                alertDialog.dismiss();
                fetchUpdateName(et_name.getText().toString());
            }
        });
    }

    private void fetchUpdateName(final String s) {
        showLoading("");
        HashMap<String, String> map = new HashMap<>();
        map.put("id", LetterApp.authUser.getId());
        map.put("nickName", s);
        map.put("token", LetterApp.authUser.getToken());
        HttpUtils.post(Constants.Url.Profile.PROFILE_UPDATE_NAME, map, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                try {
                    BaseModel baseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel>() {
                    });
                    if (baseModel.isSuccess()) {
                        showToast("修改成功");
                        LetterApp.authUser.setNickName(s);
                        tvName.setText(s);
                    } else {
                        showToast(baseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError() {
                hideLoading();
                showErrorNet();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200) {
            if (resultCode == RESULT_OK) {
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                String imagePath = path.get(0);
                if (imagePath != null) {
                    showLoading("上传照片中");
                    uploadImage(imagePath);
                } else {
                    showToast("选图失败，请重新选择");
                }

            }
        }
    }

    private void uploadImage(final String imagePath) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", LetterApp.authUser.getId());
        hashMap.put("uploadType", imageType == 0 ? "1" : "2");
        hashMap.put("token", LetterApp.authUser.getToken());
        int imageSize = imageType == 0 ? ImageUtils.DEFAULT_HEADER_SIZE : ImageUtils.DEFAULT_IMAGE_SIZE;
        HttpUtils.postFile(imageSize, Constants.Url.Profile.PROFILE_UPLOAD_HEADER, "file", new File(imagePath), hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                try {
                    BaseModel<String> baseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<String>>() {
                    });
                    if (baseModel.isSuccess()) {
                        if (imageType == 0) {
                            LetterApp.authUser.setHeadPic(imagePath);
                            ImageLoader.loadRoundImage(imagePath, ivHeader, ProfileActivity.this);

                        } else {
                            LetterApp.authUser.setBackPic(imagePath);
                            ImageLoader.loadImage(imagePath, ivBg, ProfileActivity.this);
                        }
                    } else {
                        showToast(baseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                hideLoading();
                showErrorNet();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
